package com.sharemarking.application.common.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import com.sharemarking.application.common.repository.EmployeeRepo;

import com.sharemarking.application.common.util.*;

import java.io.File;
import java.io.IOException;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;



import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.sharemarking.application.common.entity.Employee;;
/**
 * Created by Administrator on 2017/5/12.
 */

@Controller
@RequestMapping("/phone")
public class PhoneLoginController {

    @Autowired
    private EmployeeRepo dao;

   
   

    //登录方法和获取用户所有信息
    @RequestMapping(value="/plogin")
    @ResponseBody
    public Employee login( String name,String password,String stateId)throws  IOException, NoSuchAlgorithmException{
    	Employee e=new Employee();
        MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(password.getBytes());
		String pwd = new BigInteger(1,md.digest()).toString(16);  
		Employee employeeEntity = dao.findByLoginNameAndPassword(name, pwd);
        if (employeeEntity !=null){
        	employeeEntity.setStateId(stateId);
        	dao.save(employeeEntity);
        	return employeeEntity;
        	
            
           
        }else {
        	
        	return e;
           
           
        }
        
    }
    
  //修改登陆状态
    @RequestMapping(value="/changeState")
    @ResponseBody
    public void checkLogin( String name,String state)throws  IOException, NoSuchAlgorithmException{
    	
        
		Employee employeeEntity = dao.findByLoginName(name);
        if (employeeEntity !=null){
        	if(state=="false"||state.equals("false")){
        		employeeEntity.setState("true");
        		
            	dao.save(employeeEntity);
        	}else{
        		
        		employeeEntity.setState("false");
            	dao.save(employeeEntity);
        	}
        	
        	
        	
            
           
        }
        
    }
    
  //修改标识码
    @RequestMapping(value="/changeStateId")
    @ResponseBody
    public void changeStateId( String name,String stateId)throws  IOException, NoSuchAlgorithmException{
    	
        
		Employee employeeEntity = dao.findByLoginName(name);
        if (employeeEntity !=null){
       
        		employeeEntity.setStateId(stateId);
            	dao.save(employeeEntity);
        	
        	
        	
        }
        
    }
    
    
    
  //查看登陆状态
    @RequestMapping(value="/lookLogin")
    @ResponseBody
    public Employee lookLogin( String name)throws  IOException, NoSuchAlgorithmException{

    	Employee e=new Employee();
    	
		Employee employeeEntity = dao.findByLoginName(name);
        if (employeeEntity !=null){
        	
        		
        	
        	return employeeEntity;
        		
        }
        	
        	
        return e;
            
           
        
        
    }
    
    //注册方法
    @RequestMapping("/phoneReg")
    @ResponseBody
    public String PhoneReg( String loginName,String password,String Data)throws  IOException, NoSuchAlgorithmException{
    	
    	String result = "";
    	//获取classes下的路径
        String path = this.getClass().getClassLoader().getResource("").getPath()+"public/uploadImage/peopleLogo/";
        String path4 = this.getClass().getClassLoader().getResource("").getPath()+"public/uploadImage/peopleLogo";
        File file = new File(path4);
        file.mkdirs();
        //System.out.println(path);
       //图片命名为loginName+Data+8位随机数.png
		Date now = new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//可以方便地修改日期格式
		String Date = dateFormat.format( now );
		StringBuilder str=new StringBuilder();//定义变长字符串
		Random random=new Random();
		//随机生成数字，并添加到字符串
		for(int i=0;i<8;i++){
		    str.append(random.nextInt(10));
		}
	    
        String path2=path+loginName+Date+str.toString()+".png";
        String path3=loginName+Date+str.toString()+".png";
      
        Employee employeeEntity =dao.findByLoginName(loginName);
       
        if (employeeEntity !=null){
        	result = "true";
        	return result;
        }else {
          
        	Employee employeeEntity2=new Employee();
            employeeEntity2.setLoginName(loginName);
            employeeEntity2.setName(loginName);
            employeeEntity2.setPhone(loginName);
            MessageDigest md = MessageDigest.getInstance("MD5");
    		md.update(password.getBytes());
    		String pwd = new BigInteger(1,md.digest()).toString(16);
    		employeeEntity2.setPassword(pwd);
           // employeeEntity2.setCreateBy(0);
           // java.sql.Date createDate = new java.sql.Date(System.currentTimeMillis());//当前时间
            //employeeEntity2.setCreateDate(createDate);
           // employeeEntity2.setDelFlag(false);
          //  employeeEntity2.setUpdateBy(1);
           // employeeEntity2.setUpdateDate(createDate);
            employeeEntity2.setImgUrl(path3);
            employeeEntity2.setJob("暂无");
            employeeEntity2.setState("false");//登陆状态,默认为false
            boolean img=Util.GenerateImage(Data,path2);//图片解析
            if(img){
            	 dao.save(employeeEntity2);
            	 
                result = "false";
             	return result;
            }else{
            	result = "true";
            	return result;
            }
            	
           
        }
        
       
       
    }
    
 
  //验证登陆账号是否存在
    @RequestMapping("/checkPhoneNum")
    @ResponseBody
    public String checkPhoneNum( String loginName)throws  IOException{
    	
    	String result = "";
    	
        Employee employeeEntity =dao.findByLoginName(loginName);
        //System.out.println(loginName);
        if (employeeEntity !=null){
        	result = "true";
        	return result;
        	
        }else {
        	result = "false";
        	
        	return result;
        }
       
        
    }
    
    
    
    
    
  //验证登陆账号是否存在并且拿图片
    @RequestMapping("/getPhoneImg")
    @ResponseBody
    public Employee checkPhoneNumAndGetImg( String loginName)throws  IOException{
    	
    	Employee e=new Employee();
    	
        Employee employeeEntity =dao.findByLoginName(loginName);
        
        if (employeeEntity !=null){
        	
        	return employeeEntity;
        	
        }else {
        	
        	
        	return e;
        }
       
        
    }
    
	
    
    //发送验证码
    @RequestMapping("/getPhoneMassage")
    @ResponseBody
    public static String getPhoneMassage(String loginName) throws ClientException, InterruptedException {
    	String result = "";
        //发短信
        SendSmsResponse response = SmsDemo.sendSms(loginName);
        //返回的验证码phoneNum
        String phoneNum=SmsDemo.getPhoneNum();
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        Thread.sleep(3000L);

        //查明细
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = SmsDemo.querySendDetails(response.getBizId(),loginName);
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
                
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
            
            
            return phoneNum;
        }
        result="false";
        return result;
    }
    
  //验证登陆账号是否存在
    @RequestMapping("/findPassword")
    @ResponseBody
    public String findPassword( String loginName,String password)throws  IOException, NoSuchAlgorithmException{
    	
    	String result = "";
    	
        Employee employeeEntity =dao.findByLoginName(loginName);
        if (employeeEntity !=null){
        	MessageDigest md = MessageDigest.getInstance("MD5");
    		md.update(password.getBytes());
    		String pwd = new BigInteger(1,md.digest()).toString(16);
        	employeeEntity.setPassword(pwd);
        	employeeEntity.setUpdateBy(1);
        	java.sql.Date createDate = new java.sql.Date(System.currentTimeMillis());//修改时间
            employeeEntity.setUpdateDate(createDate);
            dao.save(employeeEntity);
        	result = "true";
        	return result;
        	
        }else {
        	result = "false";
        	
        	return result;
        }
       
        
    }
    
}